package com.db.exchange.demo;

import com.db.exchange.Exchange;

import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 *
 * @author nulls.narik
 */
public class DemoExchange {

    private static int search(String[] args, String arg) {
        int index = 0;
        for (String value : args) {
            if (arg.equals(value))
                return index;
            index++;
        }
        return -1;
    }

    private static final String ID_KEY = "-id";
    private static final String PORT_KEY = "-port";
    private static final String ADDRESS_KEY = "-address";

    public static void main(String[] args) throws UnknownHostException, FileNotFoundException {
        String ID = "testExchange";
        int port = 50000;
        InetAddress address = InetAddress.getLocalHost();

        int index = search(args, PORT_KEY);
        if (index >= 0 && index < args.length - 1) {
            try {
                port = Integer.valueOf(args[index + 1]);
            } catch (NumberFormatException exception) {
                port = 50000;
            }
        }

        index = search(args, ADDRESS_KEY);
        if (index >= 0 && index < args.length - 1) {
            try {
                address = InetAddress.getByName(args[index + 1]);
            } catch (NumberFormatException exception) {
                address = InetAddress.getLocalHost();
            }
        }

        index = search(args, ID_KEY);
        if (index >= 0 && index < args.length - 1) {
            ID = args[index + 1];
        }

        Exchange exchange = new Exchange(ID);
        exchange.connect(address, port);


        BufferedReader reader = new BufferedReader(new FileReader(ID));
//        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter writer = new PrintWriter(System.out, true);
        while (true) {
            try {
                String message;
                while ((message = reader.readLine()) != null) {
                    exchange.sendMessage(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
